<?php

namespace app\common\model;

use think\Config;
use think\Model;

/**
 * 抽奖记录
 */
class PrizeDraw Extends Model
{

    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';

    // 追加属性
    protected $append = [
    ];

    public function user(){
        return $this->belongsTo('User', 'user_id', 'id', [], 'LEFT')->setEagerlyType(1);
    }

    public function goods(){
        return $this->belongsTo('Goods', 'goods_id', 'id', [], 'LEFT')->setEagerlyType(1);
    }

    public function order(){
        return $this->belongsTo('Order', 'order_sn', 'order_sn', [], 'LEFT')->setEagerlyType(0);
    }

    public function cutfare(){
        return $this->hasMany('Cutfare', 'prize_draw_id', 'id');
    }


    public function getLevelWeight($map){
        $list = self::where($map)
            ->field('id,user_id')
            ->with(['user'=>function($query){
                $query->withfield('id,level');
            }])
            ->order('id')
            ->select();

        //用户幸运等级 对应种子个数 权重
        $seed = Config::get('site.user_level');
        //防止 user_level 误删，取不到，
        if (!$seed){
            $seed = [
                1 => 1,
                2 => 3,
                3 => 9,
                4 => 18,
                5 => 36,
                6 => 72,
            ];
        }

        foreach ($list as $k => $v){
            $value = 1;
            if (isset($seed[$v['user']['level']])){
                $value = $seed[$v['user']['level']];
            }
            $list[$k]['value'] = $value;
        }

        return $list;
    }

}
